package com.lv.mall.gateway.config;


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;

/**
 * 网关同一配置跨域
 * @author 吕经宇
 * @create 2021-10-16 22:05
 */
@Configuration
public class MallCorsConfiguration {


    /**
     * 使用 addAllowedOrigin 报错
     * java.lang.IllegalArgumentException:
     * When allowCredentials is true, allowedOrigins cannot contain the special value "*"since that cannot be set on the "Access-Control-Allow-Origin" response header.
     * To allow credentials to a set of origins, list them explicitly or consider using "allowedOriginPatterns" instead.
     * 	at org.springframework.web.cors.CorsConfiguration.validateAllowCredentials(CorsConfiguration.java:453) ~[spring-web-5.3.3.jar:5.3.3]
     * 	Suppressed: reactor.core.publisher.FluxOnAssembly$OnAssemblyException:
     * Error has been observed at the following site(s):
     * 	|_ checkpoint ⇢ org.springframework.cloud.gateway.filter.WeightCalculatorWebFilter [DefaultWebFilterChain]
     * 	|_ checkpoint ⇢ HTTP OPTIONS "/api/sys/login" [ExceptionHandlingWebHandler]
     * @return
     */
    @Bean   // 加入到容器中
    public CorsWebFilter corsWebFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration corsConfiguration = new CorsConfiguration();

        // 1、配置跨域
        corsConfiguration.addAllowedHeader("*"); // 允许哪些头跨域
        corsConfiguration.addAllowedMethod("*");// 允许哪些请求方式跨域
        corsConfiguration.addAllowedOriginPattern("*");// 允许哪些请求来源跨域
        corsConfiguration.setAllowCredentials(true);// 是否允许携带cookie跨域
        source.registerCorsConfiguration("/**", corsConfiguration);   // 任意路径都需要跨域配置
//        CorsConfigurationSource corsConfigurationSource = new CorsConfigurationSource() {
//            @Override
//            public org.springframework.web.cors.CorsConfiguration getCorsConfiguration(ServerWebExchange exchange) {
//                return null;
//            }
//        }
//        return new CorsWebFilter();
//    return source;
//    }?
        return new CorsWebFilter(source);
    }

    /**
     * 配置成功后
     * Access to XMLHttpRequest at 'http://localhost:88/api/sys/login' from origin 'http://localhost:8001' has been blocked by CORS policy:
     * The 'Access-Control-Allow-Origin' header contains multiple values 'http://localhost:8001, http://localhost:8001',
     * but only one is allowed.
     *
     * renren-fast 自带跨域 多添加了响应头，需要先注掉
     */
}
